package thread.noteplus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 聊天室的服务端 版本2
 *
 * 这一个版本我们利用多线程来完成与客户端的交互,使得主线程只负责接收连接即可.
 * 从而实现多个客户端可以同时连接服务端,并且每个客户端发送的消息服务端都可以接收到.
 *
 * 具体做法:
 * 1:在Server类中定义一个内部类:ClientHandler并实现Runnable接口,作为线程任务
 * 2:ClientHandler的run方法中完成原接收客户端连接后的所有操作
 *   具体包括:
 *   通过Socket获取输入流并进行流连接为BufferedReader
 *   循环通过输入流读取客户端发送过来的一行字符串并输出
 * 3:start方法中(主线程执行的操作),当调用ServerSocket的accept方法接受一个客户端连接后就
 *   启动一个线程来执行任务ClientHandler并将该Socket交给它来与该客户端交互的工作.
 *   这样一来主线程就可以立即再次循环调用accept继续等待新客户端的连接了.
 *
 * 从而实现功能要求
 *
 *
 */
public class Server  {
    private ServerSocket serverSocket;
    public Server(){
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8080);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true){
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接上了");
                Thread thread = new Thread(new ClientHandler(socket));
                thread.start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
public class ClientHandler implements Runnable{
    private Socket socket;
    private String host;

    public ClientHandler(Socket socket){
        this.socket = socket;
        host = socket.getInetAddress().getHostAddress();
    }
    @Override
    public void run(){
        try {
            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String message;
            while ((message=br.readLine())!=null){
                System.out.print(host+"说：");
                for (int i = 0; i < message.length(); i++) {
                    System.out.print(message.charAt(i));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}